//
//  RegistView.m
//  xpkc
//
//  Created by TopSageOSX on 15/3/5.
//  Copyright (c) 2015年 TopSage. All rights reserved.
//

#import "RegistView.h"
#import <QuartzCore/QuartzCore.h>

@interface RegistView (){
    UITextField *username;
    UITextField *password;
    UITextField *email;
    UITextField *phone;
    UIButton *registBtn;
    UIButton *makeButton;
}

@property (nonatomic,assign) BOOL isRead;
@end

@implementation RegistView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 创建视图
        [self creatResignView];
    }
    return self;
}

- (void)creatResignView{

    self.backgroundColor = GreenColor;
    
    CGRect frame_studyPay;
    CGRect frame_content;
    CGRect frame_usericon;
    CGRect frame_pswicon;
    CGRect frame_emailicon;
    CGRect frame_phoneicon;
    CGRect frame_username;
    CGRect frame_password;
    CGRect frame_email;
    CGRect frame_phone;
    CGRect frame_showBtn;
    CGRect frame_note;
    CGRect frame_registBtn;
    CGRect frame_prot;
    CGRect frame_protocolBtn;
    
    CGFloat offset = 20;
    
    if (isPad) {
        //
    }else{
        offset = 15;
        
        frame_studyPay      = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/7);
        frame_content       = CGRectMake(offset, SCREEN_HEIGHT/7, SCREEN_WIDTH - offset * 2, 50 * 4);
        frame_usericon      = CGRectMake(offset, 20, 20, 20);
        frame_pswicon       = CGRectMake(offset, 70, 20, 20);
        frame_emailicon     = CGRectMake(offset, 120, 20, 20);
        frame_phoneicon     = CGRectMake(offset, 170, 20, 20);
        frame_username      = CGRectMake(offset*1.5 + 20, 8, frame_content.size.width - offset *2 - 30, 40);
        frame_password      = CGRectMake(offset*1.5 + 20, 55, frame_content.size.width - offset *2 - 30 - 30, 40);
        frame_email         = CGRectMake(offset*1.5 + 20, 108, frame_content.size.width - offset *2 - 30, 40);
        frame_phone         = CGRectMake(offset*1.5 + 20, 155, frame_content.size.width - offset *2 - 30, 40);
        frame_showBtn       = CGRectMake(frame_content.size.width - offset - 32, 65, 32, 24);
        frame_note          = CGRectMake(offset, frame_content.origin.y + frame_content.size.height + offset/2, SCREEN_WIDTH - offset *2, 40);
        frame_registBtn     = CGRectMake(offset, frame_note.origin.y + frame_note.size.height+offset*2-20, SCREEN_WIDTH-offset *2, 50);
        frame_prot          = CGRectMake(90, SCREEN_HEIGHT-64-20, 85, 20);
        frame_protocolBtn   = CGRectMake(180, SCREEN_HEIGHT-64-20, 110, 20);
    }
    
    UIImageView *studypay = [[UIImageView alloc]initWithFrame:frame_studyPay];
    studypay.image = [UIImage imageNamed:@"studypay_white"];
    [self addSubview:studypay];
    
    UIView *content = [[UIView alloc]initWithFrame:frame_content];
    content.layer.cornerRadius = 5;
    content.layer.borderWidth = 1;
    content.layer.borderColor = WhiteSmokeColor.CGColor;
    content.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.3];
    [self addSubview:content];
    
    for (int i = 1; i<4; i++) {
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(offset, 50*i, content.frame.size.width - offset *2, 0.5)];
        line.backgroundColor = WhiteSmokeColor;
        [content addSubview:line];
    }//线
    
    UIImageView *usericon = [[UIImageView alloc]initWithFrame:frame_usericon];
    usericon.image = [UIImage imageNamed:@"user_white"];
    [content addSubview:usericon];
    
    UIImageView *pswicon = [[UIImageView alloc]initWithFrame:frame_pswicon];
    pswicon.image = [UIImage imageNamed:@"password_white"];
    [content addSubview:pswicon];
    
    UIImageView *emailicon = [[UIImageView alloc]initWithFrame:frame_emailicon];
    emailicon.image = [UIImage imageNamed:@"email_white"];
    [content addSubview:emailicon];
    
    UIImageView *phoneicon = [[UIImageView alloc]initWithFrame:frame_phoneicon];
    phoneicon.image = [UIImage imageNamed:@"phone_white"];
    [content addSubview:phoneicon];
    
    username = [[UITextField alloc]initWithFrame:frame_username];
    username.clearButtonMode = UITextFieldViewModeWhileEditing;
    username.placeholder = @"请输入用户名";
    username.textColor = [UIColor whiteColor];
    username.delegate = self;
    username.tag=500;
    [content addSubview:username];
    
    password = [[UITextField alloc]initWithFrame:frame_password];
//    password.clearsOnBeginEditing = YES;//注册暂时就不更改删除了
    password.secureTextEntry = YES;
    password.placeholder = @"请输入密码";
    password.textColor = [UIColor whiteColor];
    password.delegate = self;
    password.tag=501;
    [content addSubview:password];
    
    email = [[UITextField alloc]initWithFrame:frame_email];
    email.clearButtonMode = UITextFieldViewModeWhileEditing;
    email.placeholder = @"请输入注册邮箱";
    email.returnKeyType=UIReturnKeyDone;
    email.textColor = [UIColor whiteColor];
    email.delegate = self;
    email.keyboardType = UIKeyboardTypeEmailAddress;
    email.tag=502;
    [content addSubview:email];
    
    phone = [[UITextField alloc]initWithFrame:frame_phone];
    phone.clearButtonMode = UITextFieldViewModeWhileEditing;
    phone.placeholder = @"请输入手机号";
    phone.textColor = [UIColor whiteColor];
    phone.delegate = self;
    phone.keyboardType = UIKeyboardTypePhonePad;
    phone.tag=503;
    [content addSubview:phone];
    
    UIButton *showBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    showBtn.frame = frame_showBtn;
    [showBtn setImage:[UIImage imageNamed:@"password_show_white"] forState:UIControlStateNormal];
    [showBtn setImage:[UIImage imageNamed:@"password_hide_blue"] forState:UIControlStateSelected];
    [showBtn addTarget:self action:@selector(showBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [content addSubview:showBtn];
    
    UILabel *note = [[UILabel alloc]initWithFrame:frame_note];
    note.textColor = [UIColor whiteColor];
    note.numberOfLines = 0;
    note.text = @"注册成功后，可用其登录学派网及大家网相关服务站点，如大家论坛、大家网购课中心等";
    note.font = [UIFont boldSystemFontOfSize:11];
    [self addSubview:note];
    
    registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registBtn.frame = frame_registBtn;
    [registBtn setBackgroundColor:[UIColor whiteColor]];
    registBtn.layer.cornerRadius = 5;
    [registBtn setTitleColor:GreenColor forState:UIControlStateNormal];
    registBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [registBtn setTitle:@"注 册" forState:UIControlStateNormal];
    [registBtn setTitle:@"提交中" forState:UIControlStateSelected];
    [registBtn addTarget:self action:@selector(registBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:registBtn];
    
    UILabel *prot = [[UILabel alloc]initWithFrame:frame_prot];
    prot.textColor = [UIColor whiteColor];
    prot.font = [UIFont boldSystemFontOfSize:12];
    prot.text = @"我已阅读并同意";
    [self addSubview:prot];
    
    
    makeButton =[[UIButton alloc] initWithFrame:CGRectMake(60, SCREEN_HEIGHT-64-20-3, 30, 30)];
    [makeButton setImage:[UIImage imageNamed:@"isRead_waiting_selectButton@2x"] forState:(UIControlStateNormal)];
    [makeButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:makeButton];
    
    UIButton *protocolBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    protocolBtn.frame = frame_protocolBtn;
    protocolBtn.titleLabel.font = [UIFont boldSystemFontOfSize:12];
    [protocolBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
    [protocolBtn setTitle:@"《学派网用户协议》" forState:UIControlStateNormal];
    [protocolBtn addTarget:self action:@selector(protocolBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:protocolBtn];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeKeyboard)];
    [self addGestureRecognizer:tap];
}

#pragma mark - func
- (void)closeKeyboard{
    [username resignFirstResponder];
    [password resignFirstResponder];
    [email resignFirstResponder];
    [phone resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == username) {
        [password becomeFirstResponder];
    }
    if (textField == password) {
        [email becomeFirstResponder];
    }
    if (textField == email) {
        [phone becomeFirstResponder];
    }
    if (textField == phone) {
        [phone resignFirstResponder];
    }
    return YES;
}

- (void)showBtnClick:(UIButton *)btn{
    if (btn.selected) {
        password.secureTextEntry = YES;
        btn.selected = NO;
    }else{
        password.secureTextEntry = NO;
        btn.selected = YES;
    }
}

- (void)registStatue:(RegistStatue)statue{
    registBtn.selected = NO;
    
    switch (statue) {
        case RegistStatueSucc:
        {}
            break;
        case RegistStatueUsernameError:
        {}
            break;
        case RegistStatueEmailError:
        {}
            break;
        case RegistStatuePhoneError:
        {}
            break;
        case RegistStatueNetError:
        {
            ShowAlertMsg(@"网络连接错误");
        }
            break;
            
        default:
            break;
    }
}

- (void)registBtnClick:(UIButton *)btn{
    NSString *userName = username.text;
    NSString *passWord = password.text;
    NSString *Email = email.text;
    NSString *Phone = phone.text;

    if (!_isRead) {
        ShowAlertMsg(@"请勾选阅读协议选项框");
    }else{
        
        if ([self checkValidityTextField]) {
            ShowAlertMsg(@"注册成功");
            if ([self.delegate respondsToSelector:@selector(registerWithUsername:andPassword:andEmail:andPhone:)]) {
                [self.delegate registerWithUsername:userName andPassword:passWord andEmail:Email andPhone:Phone];
            }
        }else{
            //        ShowAlertMsg(@"格式不正确");
            registBtn.selected = NO;
        }

        
    }

//    if (btn.selected) {
//        //
//    }else{
//        btn.selected = YES;
//        [self checkContent];
//    }
}
- (void)protocolBtnClick:(UIButton *)btn{
    if ([self.delegate respondsToSelector:@selector(showUserProtocol)]) {
        [self.delegate showUserProtocol];
    }
}

- (BOOL)checkValidityTextField
{
    
    NSString *userName = username.text;
    NSString *passWord = password.text;
    NSString *Email = email.text;
    NSString *Phone = phone.text;
    
    if ([userName isEqualToString:@""]||userName==nil) {
        ShowAlertMsg(@"用户名不能为空");
        return NO;
    }
      if ([passWord isEqualToString:@""]||userName==nil) {
    ShowAlertMsg(@"密码不能为空");
    
        return NO;
      }else if ([passWord length]<6){
          ShowAlertMsg(@"用户密码小于6位");
          return NO;
      }
    if ([Email isEqualToString:@""]||userName==nil) {
        ShowAlertMsg(@"邮箱不能为空");
        
        return NO;
    }else if (![self isEmile]){
        ShowAlertMsg(@"邮箱格式不正确");
        return NO;
    }
    if ([Phone isEqualToString:@""]||userName==nil) {
        ShowAlertMsg(@"电话号码不能为空");
        
        return NO;
    }else if (![self isPhone]){
         ShowAlertMsg(@"手机号码不正确");
        return NO;
    }
    
    
    
    return YES;
    
}

- (void)buttonClicked:(id)sender{
    if (_isRead) {
        
        [makeButton setImage:[UIImage imageNamed:@"isRead_waiting_selectButton@2x"] forState:UIControlStateNormal];
        _isRead = NO;
    }else{
        
        [makeButton setImage:[UIImage imageNamed:@"isRead_selectedButton@2x"] forState:UIControlStateNormal];
        
        _isRead = YES;
    }


}




- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
-(BOOL)isPhone
{
    BOOL isPhone =[self isMobileNumber:phone.text];
    if (isPhone) {
        return YES;
    }else{
        return NO;
    }
}


-(BOOL)isEmile
{
    BOOL isEmile =[self isValidateEmail:email.text];
    if (isEmile) {
        return YES;
    }else{
        return NO;
    }
}


-(BOOL)isValidateEmail:(NSString *)emails

{
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    
    return [emailTest evaluateWithObject:emails];
    
}


@end
